;(function($){
/*
 * jQuery Responsiveness 0.1
 *
 * Copyright (c) 2008 Mikhail Koryak (dogself.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * 12/17/2008
 *
 *	 Makes certain types of UI much more responsive. 
 *	 If a UI requires repeated calls to a function where only the last call matters, 
 *	 for example, a UI interaction that needs to update the UI and do some costly processing,
 *	 where the costly processing needs to only happen once, but the UI interaction is repeated.
 *	 Use this plugin to improve responsiveness of such as UI.
 *	 
 *	 Settings:
 *	 interval: how often to check if a new function was queued to run, if none was queued, run the last queued. (ms)
 *	 times: how many intervals to wait between checks
 *	 
 *	 Total time before function is executed is interval * times
 *	 
 *	 example uses:
 *	 var q = $.getResponsiveness({interval:200, times:5});
 *	 var fn = function(){ /* some costly processing * };
 *	 q.run(fn, [], this);
 *
 */

$.getResponsiveness = function(conf) {
    var s = $.extend({
      interval: 200,
      times: 2
    }, conf);

    var t = null;
    var count = 0;
    var evt = null;
    var timerTicking = false;
    var enabled = true;

    var run = function(fn, args, context) {
      var args = args || [];
      var context = context || window;
      evt = {"fn": fn, "args": args, "ctx": context, "count":(count + s.times)};
      var check = function() {
        count++;
        if (evt.count == count) {
        	if(enabled) evt.fn.apply(evt.ctx, evt.args);
          timerTicking = false;
        } else {
          t = setTimeout(check, s.interval);
        }
      };
      if (!timerTicking) {
        timerTicking = true;
        t = setTimeout(check, s.interval);
      }
    };
    var reset = function() {
      clearTimeout(t); 
      evt = null;
      timerTicking = false;
    }
    var disable = function(){
    	enabled = false;
    	reset();
    }
    var enable = function(){
    	enabled = true;
    }
    var that = {};
    that.reset = reset;
    that.run = run;
    that.disable = disable;
    that.enable = enable;
    return that;
  };

})(jQuery);